import dash
import pandas as pd
import feffery_antd_components as fac
from dash import html
from dash.dependencies import Input, Output, ALL, State

from server import app

from models import db, DemoTable

layout = html.Div(
    [
        fac.AntdSpin(
            fac.AntdTable(
                id='tab6-demo-table',
                bordered=True,
                rowSelectionType='radio'
            ),
            text='数据加载中'
        ),
        fac.AntdSpace(
            [
                fac.AntdButton(
                    '增加新的数据行',
                    type='primary',
                    id={
                        'type': 'tab6-demo-button',
                        'index': 'add'
                    }
                ),
                fac.AntdButton(
                    '修改选中行',
                    id={
                        'type': 'tab6-demo-button',
                        'index': 'alter'
                    }
                ),
                fac.AntdButton(
                    '删除选中行',
                    type='primary',
                    danger=True,
                    id={
                        'type': 'tab6-demo-button',
                        'index': 'delete'
                    }
                ),
            ]
        ),
        # 反馈消息提示容器
        html.Div(id='tab6-message-container')
    ]
)


@app.callback(
    [Output('tab6-demo-table', 'columns'),
     Output('tab6-demo-table', 'data'),
     Output('tab6-message-container', 'children'),
     Output('tab6-demo-table', 'selectedRows')],
    [Input('tabs', 'activeKey'),
     Input({'type': 'tab6-demo-button', 'index': ALL}, 'nClicks')],
    State('tab6-demo-table', 'selectedRows')
)
def tab6_refresh_table(activeKey, nClicksList, selectedRows):
    # 判断当前回调由谁触发
    ctx = dash.callback_context

    if ctx.triggered[0]['prop_id'] == 'tabs.activeKey':

        if activeKey == 'tab6':
            with db.atomic():
                data = pd.DataFrame(
                    DemoTable
                        .select()
                        .dicts()
                )

            data['field3'] = data['field3'].dt.strftime('%Y-%m-%d %H:%M:%S')

            data.rename(columns={'id': 'key'}, inplace=True)

            return [
                [
                    {
                        'title': column,
                        'dataIndex': column,
                        'width': '33.3%'
                    }
                    for column in data.columns
                    if column != 'key'
                ],
                data.to_dict('records'),
                None,
                dash.no_update
            ]

    elif ctx.triggered[0]['prop_id'] == '{"index":"delete","type":"tab6-demo-button"}.nClicks':
        print(selectedRows)
        if selectedRows:
            with db.atomic():
                _ = (
                    DemoTable
                        .delete()
                        .where(DemoTable.id == selectedRows[0]['key'])
                        .execute()
                )

            with db.atomic():
                data = pd.DataFrame(
                    DemoTable
                        .select()
                        .dicts()
                )

            data['field3'] = data['field3'].dt.strftime('%Y-%m-%d %H:%M:%S')

            data.rename(columns={'id': 'key'}, inplace=True)

            return [
                [
                    {
                        'title': column,
                        'dataIndex': column,
                        'width': '33.3%'
                    }
                    for column in data.columns
                    if column != 'key'
                ],
                data.to_dict('records'),
                fac.AntdMessage(
                    content='删除成功！',
                    type='success'
                ),
                None
            ]

        return [
            dash.no_update,
            dash.no_update,
            fac.AntdMessage(
                content='请先选择要删除的行！',
                type='warning'
            ),
            dash.no_update
        ]

    return dash.no_update
